"""
Coze 智能体聊天接口
"""

from typing import Dict, Any, List, Optional
import os

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
try:
    from cozepy import (  # type: ignore
        COZE_CN_BASE_URL,
        Coze,
        TokenAuth,
        Message,
    )
    COZE_SDK_AVAILABLE = True
except ImportError:
    COZE_SDK_AVAILABLE = False
    COZE_IMPORT_ERROR = "Coze SDK 未安装，请执行 pip install cozepy"
    COZE_CN_BASE_URL = ""
    Coze = TokenAuth = Message = None

DEFAULT_COZE_API_TOKEN = "cztei_hVUx5e2L3SIf72OjqHlby4M2Scpjau2q5KZWTqr59vTibEBCcHGNRPXlFCktJmgIG"
DEFAULT_COZE_BOT_ID = "7570722189914751030"

coze_api_token = (os.getenv("COZE_API_TOKEN") or DEFAULT_COZE_API_TOKEN).strip()
coze_router = APIRouter(prefix="/coze", tags=["Coze AI"])

coze_client: Optional["Coze"] = None
if COZE_SDK_AVAILABLE:
    coze_api_base = COZE_CN_BASE_URL
    coze_bot_id = (os.getenv("COZE_BOT_ID") or DEFAULT_COZE_BOT_ID).strip()
    if coze_api_token and coze_bot_id:
        try:
            coze_client = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
        except Exception as exc:
            print(f"[WARN] 初始化 Coze 客户端失败: {exc}")
            coze_client = None
else:
    coze_bot_id = None


class CozeWorkflowRequest(BaseModel):
    input_data: Dict[str, Any]
    user_id: Optional[str] = None


def _normalize_message(msg: Message) -> Dict[str, Any]:
    meta = {}
    if hasattr(msg, "meta") and msg.meta:
        meta = msg.meta if isinstance(msg.meta, dict) else {"raw": str(msg.meta)}

    content: Any = msg.content
    if isinstance(content, list):
        rendered_parts: List[str] = []
        for part in content:
            if isinstance(part, dict):
                rendered_parts.append(part.get("text") or part.get("content") or str(part))
            else:
                rendered_parts.append(str(part))
        content_str = "\n".join([c for c in rendered_parts if c])
    else:
        content_str = str(content) if content is not None else ""

    if not meta and hasattr(msg, "file") and msg.file:
        meta = {"file": msg.file}

    return {
        "role": msg.role if hasattr(msg, "role") else "assistant",
        "content": content_str,
        "meta": meta or None,
    }


@coze_router.post("/run-workflow", summary="与 Coze 智能体对话")
async def run_coze_workflow(payload: CozeWorkflowRequest) -> Dict[str, Any]:
    if not coze_client:
        raise HTTPException(status_code=500, detail="Coze 客户端未初始化，请检查 COZE_API_TOKEN/COZE_BOT_ID")

    prompt = payload.input_data.get("prompt")
    if not prompt:
        raise HTTPException(status_code=400, detail="input_data.prompt 不能为空")

    user_id = payload.user_id or os.getenv("COZE_DEFAULT_USER_ID", "author_dashboard_user")

    try:
        chat_resp = coze_client.chat.create_and_poll(
            bot_id=coze_bot_id,
            user_id=user_id,
            additional_messages=[Message.build_user_question_text(prompt)],
        )

        assistant_messages = [
            _normalize_message(msg)
            for msg in chat_resp.messages
            if getattr(msg, "role", None) == "assistant"
        ]

        token_usage = None
        if hasattr(chat_resp, "usage") and chat_resp.usage:
            token_usage = getattr(chat_resp.usage, "token_count", None)

        return {
            "code": 200,
            "message": "智能体响应成功",
            "data": {
                "messages": assistant_messages,
                "errors": [],
                "completed": True,
                "token_usage": token_usage,
            },
        }
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"调用 Coze 智能体失败: {exc}")